package com.peng.kslc;

import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A2LengthOfLongestSubstring
 * https://ssg.leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 *
 * @author lupeng
 * Created on 2022-07-17
 */
public class A3LengthOfLongestSubstring {

    private static final Logger logger = LoggerFactory.getLogger(A3LengthOfLongestSubstring.class);

    public static void main(String[] args) {
        System.out.println(new A3LengthOfLongestSubstring().lengthOfLongestSubstring("aab"));

    }

    //public int lengthOfLongestSubstring(String s) {
    //    int max = 0;
    //    Set<Character> set = new HashSet<>();
    //    int right = -1;
    //    for (int left = 0; left < s.length(); left++) {
    //        if (left != 0) {
    //            set.remove(s.charAt(left - 1));
    //        }
    //
    //        while (right + 1 < s.length() && !set.contains(s.charAt(right + 1))) {
    //            set.add(s.charAt(right + 1));
    //            right++;
    //        }
    //        max = Math.max(max, set.size());
    //    }
    //    return max;
    //}

    //public int lengthOfLongestSubstring(String s) {
    //    int max = 0;
    //    int left = 0;
    //    while (left < s.length()) {
    //        Map<String, Integer> char2IndexMap = new HashMap<>();
    //        for (int right = left; right < s.length(); right++) {
    //            String currChar = String.valueOf(s.charAt(right));
    //            if (char2IndexMap.containsKey(currChar)) {
    //                left = char2IndexMap.get(currChar);
    //                char2IndexMap.clear();
    //                break;
    //            } else {
    //                char2IndexMap.put(currChar, right);
    //            }
    //            max = Math.max(max, char2IndexMap.size());
    //        }
    //        left++;
    //    }
    //    return max;
    //}


    public int lengthOfLongestSubstring(String s) {
        int max = 0;
        Set<Character> set = new HashSet<>();
        int left = 0;
        int right = 0;
        int length = s.length();
        while (left < length) {
            if (left != 0) {
                set.remove(s.charAt(left - 1));
            }
            while (right < length && !set.contains(s.charAt(right))) {
                set.add(s.charAt(right));
                right++;
            }
            max = Math.max(max, set.size());
            left++;
        }
        return max;
    }

}
